#!/usr/bin/env node

const http = require('http'),
      qs = require('querystring'),
      fs = require('fs'),
      formidable = require('formidable');

http.createServer((req,res)=>{
  //console.log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  //console.log(req.headers);
  console.log(`HTTP/${req.httpVersion} ${res.statusCode} ${res.statusMessage}`);
  console.log(`${res.headers}`);
  let out='';
  if(req.url==='/'){
    if(req.method==='GET'){
      res.end(uploadHtml);
    }else if(req.method==='POST'){
      const form = formidable({mutiples:true});

      form.parse(req,(err,fields,files)=>{
        console.log(fields);
        console.log(files);
      })
     /* let data='';
      req.setEncoding='binary';
      req.on('data',(chunk)=>{data+=chunk;} );
      req.on('end',()=>{
        console.log(data.split('\r\n'));
        console.log();
        //实际上得到的data长度要大于真实文件字节数，所以之后要进行解析
        console.log('req body byte length:',Buffer.byteLength(data));

        //parse data
        const filename = getFileName(data);
        const content = getFileContent(data);

        //save file
        fs.writeFileSync(filename,content);*/
        res.end(okHtml);
      }
    else{
      err(req,res);
    }
  }else{
    err(req,res);
  }
  function err(req,res){
    res.statusCode=404;
    res.end(errHtml);
  }
  
  function getFileName(data){
    let msg = data.split('\r\n');
    msg = msg[1].spilt(';');
    msg = msg[2].split('=');
    return msg[1];
  }
  function getFileContent(data){
    let msg = data.splice('\r\n');
    msg = msg.slice(4,msg.length-2);
    msg =  msg.join('\r\n');
    console.log(msg);
    return msg;
  }

}).listen(3000);

let uploadHtml=`
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>uploadHtml</title>
</head>
<body>
<form method="post" action="http://192.168.228.144:3000/">
  <label>upload file:</label>
  <input type="file" name="file">
  <br>
  <label>&nbsp;</label>
  <input type="submit" value="upload">
</form>
</body>
</html>`;
let okHtml=`
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>upload success</title>
</head>
<body>
  <h1>upload OK</h1>
</body>
</html>`;
let errHtml=`
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>upload fail</title>
</head>
<body>
  <h1>upload Fail!</h1>
</body>
</html>`;
